<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\models\{Message as Messages, Jcmessage, Business, User, Liaotian};
use think\Db;
use app\facade\Redis;

class Message extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Message')->setDescription('任务通知');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $cmd = "ps aux | grep '/www/server/php/72/bin/php /www/wwwroot/garbage/think Message'|grep -v 'grep'| awk '{print $2}'";
        exec($cmd, $ps, $ret);
        if (count($ps) > 1) {
            die("batch of  is running");
        }
        ini_set('max_execution_time', 0);
        //10分钟查询一次合同通知
        $tongzhicrons = Redis::get('tongzhicrons');
        if (!$tongzhicrons) {
            (new Business())->where('jcupdated', '< time', date('Y-m-d'))->where(['foundation' => 2, 'schedule' => 2, 'isshenhe' => 1])->chunk(5, function ($lists) {
                foreach ($lists as $list) {
                    $frtimes = Redis::get('tixingtjmessage' . $list['id']);
                    if ($frtimes ||  date('H') < 9) {
                        dump('冷却中');
                        continue;
                    }
                    $havecount = (new Jcmessage())->where(['orderid' => $list['id']])->count();
                    if ($havecount >= 2) {
                        dump('已提醒达到2次');
                        continue;
                    }
                    $have = (new Jcmessage())->where(['orderid' => $list['id'], 'date' => date('Y-m-d')])->find();
                    if (!empty($have)) {
                        dump('已通知');
                        continue;
                    }
                    Db::startTrans();
                    try {
                        (new Jcmessage())->allowfield(true)->save([
                            'orderid' => $list['id'],
                            'date' => date('Y-m-d')
                        ]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 3,
                            'orderid' => $list['id'],
                            'user_id' =>  $list['duid'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '请尽快填写合同信息！',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                    }
                    Redis::setex('tixingtjmessage' . $list['id'], 120, 120);
                }
            });
            Redis::setex('tongzhicrons', 600, 600);
        }

        //新订单通知
        (new Messages())->where(['message' => 1, 'type' => 1])->chunk(5, function ($lists) {
            $twodayend = date('Y-m-d H:i:s', time() - 0.5 * 86400);
            foreach ($lists as $list) {
                $frtimes = Redis::get('dudaomessage' . $list['id']);
                if ($frtimes) {
                    continue;
                }
                $templateid = 'asQo-LK-Wp48XFLpbiAgAcLdhVdbjpvQEomm3WXllPI';
                $business = (new Business())->where('id', $list['orderid'])->find();
                $touser = (new User())->where('id', $list['user_id'])->find();
                $openid = $touser['openid'] ?? '';
                $xcxopenid =  $touser['xcxopenid'] ?? '';
                $template = json_decode($touser['template'] ?? '', true) ?? [];
                //未公众号和小程序授权和超过12小时没有进行通知的不再通知
                if ((empty($openid) && empty($xcxopenid)) || $list['created'] <= $twodayend) {
                    (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                    continue;
                }
                if (!empty($openid) && (empty($xcxopenid) || empty($template[$templateid]['number']))) {
                    $text = '';
                    if (!empty($list['text'])) {
                        $text =  $list['text'] ?? '无';
                        if (strlen($text) >= 20) {
                            $text = mb_substr($text, 0, 17, "utf-8") . "...";
                        }
                    }
                    $name = (trim($business['name']) ?? '') . '(' . (trim($business['phone']) ?? '') . ')';
                    if (strlen($name) >= 20) {
                        $name = mb_substr($name, 0, 17, "utf-8") . "...";
                    }
                    $data = [
                        'first' => [
                            'value' => $list['text'] ?? ''
                        ],
                        'character_string1' => [
                            'value' => $list['orderid'] ?? 0
                        ],
                        'time2' => [
                            'value' =>  $list['created'] ?? date('Y-m-d H:i:s')
                        ],
                        'thing7' => [
                            'value' => $name
                        ],
                        'thing5' => [
                            'value' =>  $text ?? ''
                        ]
                    ];
                    $result = (new Messages())->message($openid, '4noOu3H1gHaD2487TF0dFULGLOppClmXdYPXi4ek6Fc', $data, config('wechat.')['app_id'], '/pages/index/index?ordermobile=' . ($business['phone'] ?? ''));
                    dump($result);
                    dump($list['id']);
                    if ($result['errcode'] == 0) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "新订单已通知2";
                    } elseif ($result['errcode'] == 43004 || $result['errcode'] == 43101) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "未订阅消息2";
                    } else {
                        Redis::setex('dudaomessage' . $list['id'], 120, 120);
                        echo '公众号' . $result['errmsg'] ?? '';
                    }
                }
            }
        });
        //报销单通知
        (new Messages())->where(['message' => 1, 'type' => 2])->chunk(5, function ($lists) {
            $twodayend = date('Y-m-d H:i:s', time() - 0.5 * 86400);
            foreach ($lists as $list) {
                $frtimes = Redis::get('dudaomessage' . $list['id']);
                if ($frtimes) {
                    continue;
                }
                $touser = (new User())->where('id', $list['user_id'])->find();
                $openid = $touser['openid'] ?? '';
                if (empty($openid) || $list['created'] <= $twodayend) {
                    (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                    continue;
                }
                if (!empty($openid)) {
                    $text = '';
                    if (!empty($list['text'])) {
                        $text =  $list['text'] ?? '无';
                        if (strlen($text) >= 20) {
                            $text = mb_substr($text, 0, 17, "utf-8") . "...";
                        }
                    }
                    $data = [
                        'thing2' => [
                            'value' => $list['text'] ?? ''
                        ],
                        'time6' => [
                            'value' =>  $list['created'] ?? date('Y-m-d H:i:s')
                        ]
                    ];
                    $result = (new Messages())->message($openid, '-Upxrrgr-7Y8BaJ-51lOkjtQkc9BhWBHteNlXHRv9dE', $data, config('wechat.')['app_id'], '/pages/index/reimburslog');
                    if ($result['errcode'] == 0) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "新订单已通知2";
                    } elseif ($result['errcode'] == 43004 || $result['errcode'] == 43101) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "未订阅消息2";
                    } else {
                        Redis::setex('dudaomessage' . $list['id'], 120, 120);
                        echo '公众号' . $result['errmsg'] ?? '';
                    }
                }
            }
        });

        //合同信息通知
        (new Messages())->where(['message' => 1, 'type' => 3])->chunk(5, function ($lists) {
            $twodayend = date('Y-m-d H:i:s', time() - 0.5 * 86400);
            foreach ($lists as $list) {
                $frtimes = Redis::get('dudaomessage' . $list['id']);
                if ($frtimes) {
                    continue;
                }
                $templateid = 'asQo-LK-Wp48XFLpbiAgAcLdhVdbjpvQEomm3WXllPI';
                $business = (new Business())->where('id', $list['orderid'])->find();
                $touser = (new User())->where('id', $list['user_id'])->find();
                $openid = $touser['openid'] ?? '';
                $xcxopenid =  $touser['xcxopenid'] ?? '';
                $template = json_decode($touser['template'] ?? '', true) ?? [];
                //未公众号和小程序授权和超过12小时没有进行通知的不再通知
                if ((empty($openid) && empty($xcxopenid)) || $list['created'] <= $twodayend) {
                    (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                    continue;
                }
                if (!empty($openid) && (empty($xcxopenid) || empty($template[$templateid]['number']))) {
                    $text = '';
                    if (!empty($list['text'])) {
                        $text =  $list['text'] ?? '无';
                        if (strlen($text) >= 20) {
                            $text = mb_substr($text, 0, 17, "utf-8") . "...";
                        }
                    }
                    $name = (trim($business['name']) ?? '') . '(' . (trim($business['phone']) ?? '') . ')';
                    if (strlen($name) >= 20) {
                        $name = mb_substr($name, 0, 17, "utf-8") . "...";
                    }
                    $data = [
                        'first' => [
                            'value' => $list['text'] ?? ''
                        ],
                        'character_string1' => [
                            'value' => $list['orderid'] ?? 0
                        ],
                        'time2' => [
                            'value' =>  $list['created'] ?? date('Y-m-d H:i:s')
                        ],
                        'thing7' => [
                            'value' => $name
                        ],
                        'thing5' => [
                            'value' =>  $text ?? ''
                        ]
                    ];
                    $result = (new Messages())->message($openid, '4noOu3H1gHaD2487TF0dFULGLOppClmXdYPXi4ek6Fc', $data, config('wechat.')['app_id'], '/pages/index/xuanzhi_new?id=' . ($list['orderid'] ?? ''));
                    dump($result);
                    dump($list['id']);
                    if ($result['errcode'] == 0) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "新订单已通知2";
                    } elseif ($result['errcode'] == 43004 || $result['errcode'] == 43101) {
                        (new Messages())->where(['id' => $list['id']])->update(['message' => 2]);
                        echo "未订阅消息2";
                    } else {
                        Redis::setex('dudaomessage' . $list['id'], 120, 120);
                        echo '公众号' . $result['errmsg'] ?? '';
                    }
                }
            }
        });

        $lists =  (new Liaotian())->distinct(true)->field('touser_id,reimbursid,type')->where(['message' => 1, 'isdel' => 1])->select();
        foreach ($lists as $list) {
            $frtimes = Redis::get('liaotianmessage' . $list['reimbursid']);
            if ($frtimes) {
                continue;
            }
            $touser = explode(',', $list['touser_id']) ?? [];
            $openids = (new User())->whereNotNull('openid')->where(['id' => $touser])->column('openid') ?? [];
            $data = [
                'thing2' => [
                    'value' => '新的回复消息，前往查看'
                ],
                'time6' => [
                    'value' =>  $list['created'] ?? date('Y-m-d H:i:s')
                ]
            ];
            (new Liaotian())->where(['touser_id' => $list['touser_id'], 'reimbursid' => $list['reimbursid'], 'type' => $list['type']])->update(['message' => 2]);
            foreach ($openids as $openid) {
                $result = (new Messages())->message($openid, '-Upxrrgr-7Y8BaJ-51lOkjtQkc9BhWBHteNlXHRv9dE', $data, config('wechat.')['app_id'], '/pages/index/liaotian?id=' . $list['reimbursid']);
                if ($result['errcode'] == 43004 || $result['errcode'] == 43101) {
                    echo "未订阅消息2";
                } else {
                    Redis::setex('liaotianmessage' . $list['reimbursid'], 120, 120);
                    echo '公众号' . $result['errmsg'] ?? '';
                }
            }
        }
    }
}
